package com.vv.vv_commonlibrary.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import com.vv.vv_commonlibrary.R;

public class DotLineView extends View {

    public DotLineView(Context context) {
        super(context);
        intiPaint(context, null);
    }

    public DotLineView(Context context, AttributeSet attrs) {
        super(context, attrs);
        intiPaint(context, attrs);
    }

    private int dotLineHeight;
    private int dotRadius = 4;
    private int dotInterval = 8;

    private Paint linePaint;
    private Paint dotPaint;

    private void intiPaint(Context context, AttributeSet attrs) {

        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.DotLineView);
        int dotLineColor = attributes.getColor(R.styleable.DotLineView_dotLineColor, -1);
        dotLineHeight = attributes.getDimensionPixelSize(R.styleable.DotLineView_dotLineHeight, -1);
        int dotColor = attributes.getColor(R.styleable.DotLineView_dotColor, -1);
        dotRadius = attributes.getDimensionPixelSize(R.styleable.DotLineView_dotRadius, -1);
        dotInterval = attributes.getDimensionPixelSize(R.styleable.DotLineView_dotInterval, -1);
        attributes.recycle();

        linePaint = new Paint();
        linePaint.setColor(dotLineColor);
        linePaint.setAntiAlias(true);
        linePaint.setStyle(Paint.Style.FILL);
        linePaint.setStrokeCap(Paint.Cap.BUTT);

        dotPaint = new Paint();
        dotPaint.setColor(dotColor);
        dotPaint.setAntiAlias(true);
        dotPaint.setStyle(Paint.Style.FILL);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(widthMeasureSpec, dotRadius * 2);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();

        int diameter = dotRadius * 2;
        int height = getHeight() > diameter ? getHeight() : diameter;
        int centerY = height / 2;

        //使用RectF构造
        RectF rect = new RectF(0f, centerY - dotLineHeight / 2f, width, centerY + dotLineHeight / 2f);
        canvas.drawRect(rect, linePaint);

        int count = width / (diameter + dotInterval) - 1;

        int start = (width - (diameter + dotInterval) * count) / 2;

        for (int i = start + dotRadius; i < width - start; i = i + diameter + dotInterval) {
            canvas.drawCircle(i, centerY, dotRadius, dotPaint);
        }

    }
}
